package com.example.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.example.login.entity.dto.EmployeeDto;
import com.example.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.utils.RedisConstants.LOGIN_Employee_KEY;
import static com.example.utils.RedisConstants.LOGIN_USER_KEY;

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("访问第一拦截器资源");

        //1.获取请求头中的token
        String token = request.getHeader("authorization");
        log.info("生成的token{}",token);
        if (StrUtil.isBlank(token)){
            return true;
        }
        //2.基于用户id获取redis用户
        String key = LOGIN_Employee_KEY + token;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        log.info("用户是否存在：{}",userMap);
        //3.判断用户是否存在
        if (userMap.isEmpty()){
            return true;
        }
        //4.将查询到的Hash数据转为UserDto对象
        EmployeeDto employeeDto = BeanUtil.fillBeanWithMap(userMap, new EmployeeDto(), false);
        //5.存在，保存用户信息到ThreadLocal
        UserHolder.saveEmployeeDto(employeeDto);
        System.out.println(employeeDto);

        //6.刷新token有效期
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_Employee_TTL, TimeUnit.MINUTES);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeEmployeeDto();
    }
}
